namespace Game {
    using System.Collections;

    using UnityEngine;

    public static class Application {
        public static IEnumerator OnInit() {
            if (bInited) {
                yield return Map.Now.OnLoaded(); yield break;
            }

#if UNITY_EDITOR
            Updater.Progress = 1.0f;
            yield return Assets.OnInit(null);
            OnPrepared();
            yield return InitSubSystem();
#else
            AssetBundleManifest manifest = null;
            yield return Updater.OnInit(o => manifest = o);
            yield return Assets.OnInit(manifest);
            Updater.Clear();
            OnPrepared();
            yield return InitSubSystem();
#endif
        }

        public static void OnShutdown() {
        }

        public static void OnPrepared() {
            Logger.Info("Application: resource prepared");

            System.AppDomain.CurrentDomain.UnhandledException += (object sender, System.UnhandledExceptionEventArgs e) => {
                Logger.Exception((System.Exception)e.ExceptionObject);
            };
        }

        public static IEnumerator InitSubSystem() {
            yield return Logger.OnInit();

            Logger.Info("Init sub systems.");

            yield return Lua.OnInit();

#if !UNITY_EDITOR
            yield return Downloader.OnInit();
#endif
            yield return Map.OnInit();

            yield return CanvasCamera.OnInit();

            bInited = true;

            yield return Map.Now.OnLoaded();
        }

        private static bool bInited = false;
    }
}
